package com.iking.toolkit.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

@EnableWebMvc
@Configuration
class WebMvcConfig implements WebMvcConfigurer {
    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Value("${spring.jackson.time-zone:GMT+8}")
    private String zone;
    /**
     * 在配置文件中配置的文件保存路径
     */
    @Value("${files.location}")
    private String files;

    /**
     * 静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 映射静态资源：将 /ofdViewer/** 路径映射到 resources/static/ofdViewer/ 目录
        registry.addResourceHandler("/ofdViewer/**")
                .addResourceLocations("classpath:/static/ofdViewer/");

        // 若需要更通用的映射（映射所有static下的资源）：
        // registry.addResourceHandler("/**")
        //         .addResourceLocations("classpath:/static/");

    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        List<MediaType> supportMediaTypeList = new ArrayList<>();
        supportMediaTypeList.add(MediaType.APPLICATION_JSON);
        supportMediaTypeList.add(MediaType.APPLICATION_ATOM_XML);
        supportMediaTypeList.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportMediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);

        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);

        // 统一处理时区和时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        dateFormat.setTimeZone(TimeZone.getTimeZone(zone));
        // 全局指定了日期格式
        config.setDateFormat(dateFormat.toPattern());

        converter.setFastJsonConfig(config);
        converter.setSupportedMediaTypes(supportMediaTypeList);
        converter.setDefaultCharset(StandardCharsets.UTF_8);

        // 增加二进制转换器,解决Spring doc的问题。
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(converter);
    }
}
